<template>
  <div>
    <div style="margin-top: 10px">
      <BasicForm @register="registerForm" @submit="searchButton" />
    </div>
    <div>
      <a-list
        size="small"
        :bordered="false"
        :split="false"
        :data-source="searchArticles.articles"
        style="background-color: white"
      >
        <template #renderItem="{ item }">
          <a-list-item>
            <span
              class="category-article-title"
              @click="onClickArticleTitle(item)"
              style="cursor: pointer"
            >
              {{ item.title }}
            </span>
            <span class="category-article-time">{{
              item.intm != null && item.intm.length > 10 ? item.intm.slice(0, 10) : item.intm
            }}</span>

            <!-- <span @click="onClickArticleTitle(item)">
              <span style="color: rgba(235, 0, 8, 0.944)">{{ item.keywords }}</span>
              _
              <span style="color: rgba(5, 5, 233, 0.641)">
                {{ item.title }}
              </span>
              <p v-if="item.source != null || item.author != null">
                <span v-if="item.source != null">&nbsp;来源：{{ item.source }}</span>
                &nbsp;
                <span v-if="item.author != null">作者：{{ item.author }}</span>
              </p>
            </span> -->
          </a-list-item>
          <hr />
        </template>
      </a-list>
    </div>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, onBeforeMount, onMounted, onUnmounted } from 'vue';

  import { useRouter } from 'vue-router';

  import { useGo } from '/@/hooks/web/usePage';
  import { useCmsStore } from '/@/store/modules/cms';

  import { queryArticles } from '/@/api/cms/display';
  import { ArticleQueryConditionDto } from '/@/api/cms/model/articleModel';

  import { articlesQueryConditionFormSchema } from './articles/articles.data';
  import { BasicForm, useForm } from '/@/components/Form/index';

  import { queryListSimple } from '/@/api/cms/category';
  import { viewArticle } from '/@/api/cms/article';
  import { CategoryQueryConditionDto } from '/@/api/cms/model/categoryModel';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'ArticleSearch',
    components: { BasicForm },
    setup() {
      const router = useRouter();
      const go = useGo();
      const cmsStore = useCmsStore();

      const searchKeyword = ref<String>('');
      const searchArticles = reactive({ articles: [] });

      const [registerForm, { setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        schemas: articlesQueryConditionFormSchema,
        showActionButtonGroup: true,
        actionColOptions: {
          span: 23,
        },
      });

      onBeforeMount(() => {
        console.log(
          'CmsSearchArticleView onBeforeMount route params',
          router.currentRoute.value.params,
        );
        //从路由获取参数
        if (router.currentRoute.value.params.keywords) {
          searchKeyword.value = router.currentRoute.value.params.keywords;
        }

        getAllValidCategories();
      });
      onMounted(() => {
        //必须要在onMounted中，否则表单还没有加载到前端，无法使用表单中的方法
        //设置表单数据
        setFieldsValue({
          keywords: searchKeyword.value,
        });

        //搜索文章
        querySearchArticles();
      });
      onUnmounted(() => {
        console.log('CmsSearchArticleView onUnmounted');
      });

      /**
       * 根据关键字查询新闻
       */
      function querySearchArticles() {
        let condition: ArticleQueryConditionDto = {
          keywords: searchKeyword.value,
          page: 1,
          pageSize: 10,
        };
        queryArticles(condition)
          .then((res) => {
            console.log('getDisplaySearchArticles res', res);
            searchArticles.articles = res.items;
          })
          .catch((ex) => {
            console.log('getDisplaySearchArticles ex', ex);
          });
      }

      /**
       * 点击文章标题事件，根据文章内容类型进行不同处理；文章类型为超链接时打开新窗口，为其他类型时跳转至文章查看页面
       * @param article 文章信息
       */
      function onClickArticleTitle(article) {
        // console.log('onClickArticleTitle', article);
        if (!article) {
          //文章信息为空无法进行后继处理
        } else {
          if (article.ctype === 3 || article.ctype === '3') {
            //文章内容类型为超链接，打开新窗口
            viewArticle({ id: article.id }).then((res) => {
              window.open(res.content);
            });
          } else {
            //使用store存储跳转路由需传递的数据
            // cmsStore.setCmsRouteParam({
            //   isArticle: true,
            //   id: article.id,
            //   data: article,
            // });
            // go('/cms/article/' + article.id);
            //打开一个新的浏览器窗口
            const url = router.resolve({
              path: '/cms/article/' + article.id,
            });
            window.open(url.href);
          }
        }
      }

      /**
       * 表单查询按钮查询
       */
      async function searchButton() {
        const values = await validate();
        queryArticles(values)
          .then((res) => {
            console.log('getDisplaySearchArticles res', res);
            searchArticles.articles = res.items;
          })
          .catch((ex) => {
            console.log('getDisplaySearchArticles ex', ex);
          });
      }

      /**
       * 查询有效栏目信息，显示栏目下拉列表
       */
      function getAllValidCategories() {
        //显示的栏目信息包含有效状态，但不根据用户所在部门进行过滤
        let queryConditionDto: CategoryQueryConditionDto = {
          isall: false,
          isdept: false,
        };
        //父栏目选项集合
        let categoryOptions = [];
        queryListSimple(queryConditionDto)
          .then((res) => {
            // console.log('res', res);
            res.forEach((category) => {
              //options的value类型必须与表单中对应字段的类型一致，否则无法自动选中
              let categoryId: number = category.id as number;
              //根据层级在栏目名称前添加空格，实测空格无效，显示时没有空格
              let prefixSpaces = '';
              for (let index = 1; index < category.level; index++) {
                prefixSpaces += '---';
              }
              categoryOptions.push({ value: categoryId, label: prefixSpaces + category.name });
            });

            // updateSchema({
            //   field: 'keywords',
            //   // component: 'Select',
            //   defaultValue: searchKeyword.value,
            // });

            //设置栏目下拉列表
            updateSchema({
              field: 'cid',
              componentProps: {
                options: categoryOptions,
              },
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      return {
        querySearchArticles,
        searchArticles,
        onClickArticleTitle,
        registerForm,
        searchButton,
        getAllValidCategories,
      };
    },
  });
</script>
<style scoped lang="less">
  @import './cms.less';
  //覆盖antd的默认演示，解决头部高度过大的问题
  .ant-list:deep(.ant-list-header) {
    // line-height: 1;
    padding-bottom: 0px;
  }
</style>
